﻿@{
    ViewBag.Title = "ProductDetail";
    Layout = "~/Areas/Admin/Views/Shared/_AdminLayout.cshtml";
    var lstProductBrand = (List<XukaShop.Models.Entities.Brand>)ViewBag.BrandList;
    var lstGender = (List<XukaShop.Models.Entities.Gender>)ViewBag.GenderList;
    var lstSize = (List<XukaShop.Models.Entities.Size>)ViewBag.SizeList;
    var lstProductSize = (List<int>)ViewBag.ProductSize;
    var lstProductType = (List<XukaShop.Models.Entities.ProductType>)ViewBag.ProductTypeList;
    bool isHasImage = (bool)ViewBag.IsHaveImage;
    string modeShowForImageDiv = "none";
    if (isHasImage)
    {
        modeShowForImageDiv = "normal";
    }
    bool isInputedSizeQuantity = (bool)ViewBag.IsInputedSizeQuantity;
    string isShowInputSizeQuantity = "none";
    if (isInputedSizeQuantity)
    {
        isShowInputSizeQuantity = "normal";
    }
    var lstLocation = (List<XukaShop.Models.Entities.Location>)ViewBag.LocationList;
}

@model XukaShop.Models.ConcertModel.ProductConcert

<link href="~/Areas/Admin/js/dropzone/css/dropzone.css" rel="stylesheet" />

<style type="text/css">
    .dz-max-files-reached {
        background-color: red;
    }
</style>

@section Breadcrumbs
{
    <div class="media">
        <div class="pageicon pull-left">
            <i class="fa fa-home"></i>
        </div>
        <div class="media-body">
            <ul class="breadcrumb">
                <li><a href="@Url.Action("Index", "Dashboard")"><i class="glyphicon glyphicon-home"></i></a></li>
                <li><a href="@Url.Action("Index", "Dashboard")">Trang chủ</a></li>
                <li><a href="@Url.Action("ProductList", "Product")">Tất cả sản phẩm</a></li>
            </ul>
            <h4>Chi tiết sản phẩm</h4>
        </div>
    </div>
}

@section MenuBar
{
    <h5 class="leftpanel-title">Menu</h5>
    <ul class="nav nav-pills nav-stacked">
        <li><a href="@Url.Action("Index", "Dashboard")"><i class="fa fa-home"></i><span>Trang chủ</span></a></li>
        <li><a href="@Url.Action("Index", "Order")"><i class="glyphicon glyphicon-shopping-cart"></i><span>Đặt hàng</span></a></li>
        <li><a href="@Url.Action("Index", "Message")"><i class="glyphicon glyphicon-envelope"></i><span>Tin nhắn</span></a></li>
        <li class="parent active"><a href="#"><i class="fa fa-file-text"></i><span>Sản phẩm</span></a>
            <ul class="children">
                <li class="active"><a href="@Url.Action("ProductList", "Product")">Tất cả sản phẩm</a></li>
                <li><a href="@Url.Action("NewProduct", "Product")">Sản phẩm mới</a></li>
                <li><a href="@Url.Action("CommingSoonProduct", "Product")">Sản phẩm sắp có</a></li>
                <li><a href="@Url.Action("Index", "Brand")">Nhãn hàng</a></li>
            </ul>
        </li>
        <li><a href="@Url.Action("Index", "Promotion")"><i class="glyphicon glyphicon-bullhorn"></i><span>Giảm giá</span></a></li>
        <li><a href="@Url.Action("MemberList", "Member")"><i class="glyphicon glyphicon-user"></i><span>Thành viên</span></a></li>
        <li class="parent"><a href="#"><i class="fa fa-file-text"></i><span>Quản lý chung</span></a>
            <ul class="children">
                <li><a href="@Url.Action("Index", "Banner")">Banners</a></li>
            </ul>
        </li>
    </ul>
}

<div class="row">
    <div class="col-sm-12 col-md-12">
        <div class="panel panel-default">
            <div class="panel-heading">
                <h4 class="panel-title">Chi tiết sản phẩm</h4>
            </div>
            <div class="panel-body nopadding">
                <form class="form-horizontal form-bordered" id="frmProductDetail">
                    <div class="row">
                        <div class="col-sm-6">
                            <div class="form-group">
                                <label class="col-sm-3 control-label">Mã sản phẩm</label>
                                <div class="col-sm-8">
                                    @Html.TextBoxFor(model => model.Product.ProductCode, null, new { @class = "form-control", @id = "txtProductCode", @readonly = "true" })
                                </div>
                            </div>
                        </div>
                        <div class="col-sm-6">
                            <div class="form-group">
                                <label class="col-sm-3 control-label">Giới tính</label>
                                <div class="col-sm-8">
                                    <select id="cbbGender" name="cbbGender" data-placeholder="Choose One" class="width300">
                                        <option value=""></option>
                                        @foreach (var gender in lstGender)
                                        {
                                            if (Model.Product != null && gender.Id.Equals(Model.Product.GenderId))
                                            {
                                            <option value="@gender.Id" selected>@gender.Name</option>
                                            }
                                            else
                                            {
                                            <option value="@gender.Id">@gender.Name</option>
                                            }
                                        }
                                    </select>
                                </div>
                            </div>
                        </div>
                    </div>

                    <div class="row">
                        <div class="col-sm-6">
                            <div class="form-group">
                                <label class="col-sm-3 control-label">Tên sản phẩm</label>
                                <div class="col-sm-8">
                                    @Html.TextBoxFor(model => model.Product.ProductName, null, new { @class = "form-control", @id = "txtProductName" })
                                </div>
                            </div>
                        </div>

                        <div class="col-sm-6">
                            <div class="form-group">
                                <label class="col-sm-3 control-label">Nhãn hàng</label>
                                <div class="col-sm-8">
                                    <select id="cbbProductBrand" name="cbbProductBrand" data-placeholder="Choose One" class="width300">
                                        <option value=""></option>
                                        @foreach (var brand in lstProductBrand)
                                        {
                                            if (Model.Product != null && brand.Id.Equals(Model.Product.BrandId))
                                            {
                                            <option value="@brand.Id" selected>@brand.BrandName</option>
                                            }
                                            else
                                            {
                                            <option value="@brand.Id">@brand.BrandName</option>
                                            }
                                        }
                                    </select>
                                </div>
                            </div>
                        </div>
                    </div>

                    <div class="row">
                        <div class="col-sm-6">
                            <div class="form-group">
                                <label class="col-sm-3 control-label">Giá mua về</label>
                                <div class="col-sm-8">
                                    @Html.TextBoxFor(model => model.Product.PurePrice, null, new { @class = "form-control", @id = "txtPurePrice" })
                                </div>
                            </div>
                        </div>
                        <div class="col-sm-6">
                            <div class="form-group">
                                <label class="col-sm-3 control-label">Trạng Thái</label>
                                <div class="col-sm-8">
                                    <select id="cbbProductType" name="cbbProductType" data-placeholder="Choose One" class="width300">
                                        <option value=""></option>
                                        @foreach (var productType in lstProductType)
                                        {
                                            if (Model.Product != null && productType.Id.Equals(Model.Product.ProductTypeId))
                                            {
                                            <option value="@productType.Id" selected>@productType.Name</option>
                                            }
                                            else
                                            {
                                            <option value="@productType.Id">@productType.Name</option>
                                            }
                                        }
                                    </select>
                                </div>
                            </div>
                        </div>
                    </div>

                    <div class="row">
                        <div class="col-sm-6">
                            <div class="form-group">
                                <label class="col-sm-3 control-label">Giá bán ra</label>
                                <div class="col-sm-8">
                                    @Html.TextBoxFor(model => model.Product.SalePrice, null, new { @class = "form-control", @id = "txtSalePrice" })
                                </div>
                            </div>
                        </div>
                        <div class="col-sm-6">
                            <div class="form-group">
                                <label class="col-sm-3 control-label">Số lượng</label>
                                <div class="col-sm-8">
                                    @Html.TextBoxFor(model => model.Product.Quantity, null, new { @class = "form-control", @id = "txtProductQuantity" })
                                </div>
                            </div>
                        </div>
                    </div>

                    <div class="row">
                        <div class="col-sm-6">
                            <div class="form-group">
                                <label class="col-sm-3 control-label">Ngày nhập kho</label>
                                <div class="col-sm-8">
                                    <div class="input-group">
                                        <input type="text" name="Product.DateInput" class="form-control" value="@DateTime.Today.ToString("MM/dd/yyyy")" placeholder="Ngày/Tháng/Năm" id="txtDateInput" readonly="true">
                                        <span class="input-group-addon"><i class="glyphicon glyphicon-calendar"></i></span>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div class="col-sm-6">
                            <div class="form-group">
                                <label class="col-sm-3 control-label">Size</label>
                                <div class="col-sm-5">
                                    <select id="multiCbbProductSize" name="multiCbbProductSize" data-placeholder="Choose One" multiple class="width250">
                                        @foreach (var size in lstSize)
                                        {
                                            if (Model.Product != null && lstProductSize.Contains(size.Id))
                                            {
                                            <option value="@size.Id" selected>@size.SizeName</option>
                                            }
                                            else
                                            {
                                            <option value="@size.Id">@size.SizeName</option>
                                            }
                                        }
                                    </select>
                                </div>
                                <div class="col-sm-3">
                                    <button type="button" id="inputSizeQuantity" class="btn btn-primary mr5" data-toggle="modal" data-target=".product-size" onclick="loadProductSize()" style="display: @isShowInputSizeQuantity">
                                        Nhập số lượng
                                        <br />
                                        cho từng Size</button>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="row">
                        <div class="col-sm-6">
                            <div class="form-group">
                                <label class="col-sm-3 control-label">Chi nhánh</label>
                                <div class="col-sm-8">
                                    <select id="multiCbbProductLocation" name="multiCbbProductLocation" data-placeholder="Choose One" multiple class="width300">
                                        <option value=""></option>
                                        @foreach (var location in lstLocation)
                                        {
                                            if (Model.ListLocationId != null && Model.ListLocationId.Contains(location.Id.ToString()))
                                            {
                                            <option value="@location.Id" selected>@location.Name</option>
                                            }
                                            else
                                            {
                                            <option value="@location.Id">@location.Name</option>
                                            }
                                        }
                                    </select>
                                </div>
                            </div>
                        </div>
                        <div class="col-sm-6">
                            <div class="form-group">
                                <label class="col-sm-3 control-label">Miêu tả</label>
                                <div class="col-sm-8">
                                    @Html.TextAreaFor(model => model.Product.Description, new { @class = "form-control" })
                                </div>
                            </div>
                        </div>
                    </div>
                    @Html.HiddenFor(model => model.Product.BrandId, new { @id = "txtBrandId" })
                    @Html.HiddenFor(model => model.Product.Quantity, new { @id = "txtProductQuantity" })
                    @Html.HiddenFor(model => model.ListSizeId, new { @id = "txtListSizeId" })
                    @Html.HiddenFor(model => model.Product.GenderId, new { @id = "txtGenderId" })
                    @Html.HiddenFor(model => model.Product.ProductTypeId, new { @id = "txtProductTypeId" })
                    @Html.HiddenFor(model => model.ListLocationId, new { @id = "txtListLocationId" })
                </form>
            </div>
            <div class="panel-footer">
                <div class="row">
                    <div class="col-sm-12">
                        <button class="btn btn-primary mr5" id="btnSaveGeneralInfo" type="button" onclick="saveProductInfo()">Lưu</button>
                        @Html.ActionLink("Quay lại", "ProductList", "Product", new { @class = "btn btn-dark" })
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Modal Popup for Product Size -->
<div class="modal fade product-size" tabindex="-1" role="dialog" data-backdrop="static" id="lstProductSize">
    @Html.Partial("_ProductSize", new List<XukaShop.Models.Entities.ProductSize>())
</div>

<div class="row" style="display: @modeShowForImageDiv" id="productImage" >
    <div class="col-sm-12 col-md-12">
        <div class="panel panel-default">
            <div class="panel-heading">
                <h4 class="panel-title">Ảnh sản phẩm</h4>
            </div>
            <div class="panel-body nopadding">
                <form action="@Url.Action("UploadImageProduct", "Product")" method="post" enctype="multipart/form-data" class="dropzone" id="dropzoneForm">
                    <div class="fallback">
                        <input name="file" type="file" multiple />
                        <input type="submit" value="Upload" />
                    </div>
                </form>
            </div>
            <div class="panel-footer">
                <div class="row">
                    <div class="col-sm-12">
                        @Html.ActionLink("Quay lại", "ProductList", "Product", new { @class = "btn btn-dark" })
                    </div>
                </div>
            </div>
        </div>
    </div>
    <input type="text" id="txtProductImageInfo" style="display: none" />
</div>

<script src="~/Areas/Admin/js/dropzone/dropzone.min.js"></script>
<script type="text/javascript">
    jQuery(document).ready(function () {
        // Date Picker
        jQuery('#txtDateInput').datepicker();

        jQuery('#multiCbbProductSize').select2({});
        jQuery('#cbbGender').select2({});
        jQuery('#cbbProductBrand').select2({});
        jQuery('#cbbProductType').select2({});
        jQuery('#multiCbbProductLocation').select2({});

        // Basic Form
        jQuery("#frmProductDetail").validate({
            rules: {
                "Product.ProductName": {
                    required: true,
                    minlength: 1,
                    maxlength: 50
                },
                "Product.Quantity": {
                    required: true,
                    number: true,
                    min: 1
                },
                "Product.PurePrice": {
                    required: true,
                    number: true,
                    min: 1
                },
                "Product.SalePrice": {
                    required: true,
                    number: true,
                    min: 1
                },
                cbbGender: {
                    required: true
                },
                cbbProductBrand: {
                    required: true
                },
                cbbProductType: {
                    required: true
                },
                "Product.DateInput": {
                    required: true
                },
                multiCbbProductSize: {
                    required: true
                },
                multiCbbProductLocation: {
                    required: true
                }
            },
            messages: {
                "Product.ProductName": {
                    required: "Xin hãy nhập tên cho sản phẩm!",
                    minlength: "Tên sản phẩm có ít nhất 1 ký tự",
                    maxlength: "Tên sản phẩm có nhiều nhất 50 ký tự"
                },
                "Product.Quantity": {
                    required: "Xin hãy nhập số lượng cho sản phẩm!",
                    number: "Xin hãy nhập số!",
                    min: "Số lượng sản phẩm ít nhất là 1!"
                },
                "Product.PurePrice": {
                    required: "Xin hãy nhập giá mua về!",
                    number: "Xin hãy nhập số!",
                    min: "Giá thấp nhất là 1!"
                },
                "Product.SalePrice": {
                    required: "Xin hãy nhập giá bán ra!",
                    number: "Xin hãy nhập số!",
                    min: "Giá thấp nhất là 1!"
                },
                "Product.DateInput": {
                    required: "Xin hãy chọn ngày nhập hàng!"
                },
                cbbGender: {
                    required: "Xin hãy chọn giới tính cho sản phẩm!"
                },
                cbbProductBrand: {
                    required: "Xin hãy chọn nhãn hàng cho sản phẩm!"
                },
                cbbProductType: {
                    required: "Xin hãy chọn trạng thái sản phẩm!"
                },
                multiCbbProductSize: {
                    required: "Xin hãy chọn size cho sản phẩm!"
                },
                multiCbbProductLocation: {
                    required: "Xin hãy chọn chi nhánh cho sản phẩm!"
                }
            },
            highlight: function (element) {
                jQuery(element).closest('.form-group').removeClass('has-success').addClass('has-error');
            },
            success: function (element) {
                jQuery(element).closest('.form-group').removeClass('has-error');
                jQuery(element).remove();
            }
        });
    });

    function GetListProductImage(dropzone) {
        var productCode = $("#txtProductCode").val();
        $.ajax({
            url: '@Url.Action("GetListImageProduct", "Product")',
            dataType: 'json',
            contentType: 'application/json',
            data: { productCode: productCode },
            success: function (data) {
                $.each(data, function (index, image) {
                    var mockFile = { name: image.ImageName, size: 12345 };
                    // Call the default addedfile event handler
                    dropzone.emit("addedfile", mockFile);
                    var imagePath = "/Images/ProductImage/" + image.ImagePath;
                    // And optionally show the thumbnail of the file:
                    dropzone.emit("thumbnail", mockFile, imagePath);
                    // file must be added manually
                    dropzone.files.push(mockFile);

                    // If you use the maxFiles option, make sure you adjust it to the
                    // correct amount:
                    var existingFileCount = 1; // The number of files already uploaded
                    dropzone.options.maxFiles = dropzone.options.maxFiles - existingFileCount;

                    var productImageInfo = $('#txtProductImageInfo').val();
                    if (productImageInfo == "") {
                        productImageInfo = image.ProductImageInfor + ",";
                    }
                    else {
                        if (image.IsFinalItem == true) {
                            productImageInfo = productImageInfo + image.ProductImageInfor;
                        }
                        else {
                            productImageInfo = productImageInfo + image.ProductImageInfor + ",";
                        }
                    }
                    $('#txtProductImageInfo').val(productImageInfo);
                });
            },
            error: function () {
                alert("Fail");
            }
        });
    }

    // Upload Product Image
    Dropzone.options.dropzoneForm = {
        maxFiles: 5,
        paramName: "file", // The name that will be used to transfer the file
        maxFilesize: 2, // MB
        dictMaxFilesExceeded: "Bạn chỉ được upload tối đa 5 ảnh",
        init: function () {
            GetListProductImage(this);

            this.on("maxfilesexceeded", function (data) {
                var res = eval('(' + data.xhr.responseText + ')');
            });
            this.on("sending", function (file, xhr, formData) {
                var productCode = $('#txtProductCode').val();
                formData.append("productCode", productCode);
            });
            this.on("addedfile", function (file) {
                // Create the remove button
                var removeButton = Dropzone.createElement("<button>Remove file</button>");

                // Capture the Dropzone instance as closure.
                var _this = this;

                // Listen to the click event
                removeButton.addEventListener("click", function (e) {
                    // Make sure the button click doesn't submit the form:
                    e.preventDefault();
                    e.stopPropagation();

                    // Remove Product Image
                    if (removeImage(file) == true) {
                        // Remove the file preview.
                        _this.removeFile(file);
                    }
                });

                // Add the button to the file preview element.
                file.previewElement.appendChild(removeButton);
            });
            this.on("success", function (file, responseText) {
                saveImageInfo(file.name, responseText.Message);
                showMessageAddImageSuccess();
            });
            this.on("error", function (file) {
                showMessageAddImageError();
            });
        }
    };

    function showMessageAddImageError() {
        jQuery.gritter.add({
            title: 'Thất bại!',
            text: 'Không thể thêm ảnh sản phẩm! Xin hãy thử lại!',
            class_name: 'growl-danger',
            sticky: false,
            time: '1000'
        });
        return false;
    }

    function showMessageAddImageSuccess() {
        jQuery.gritter.add({
            title: 'Thành công!',
            text: 'Xóa ảnh sản phẩm thành công!',
            class_name: 'growl-success',
            sticky: false,
            time: '1000'
        });
        return false;
    }

    // Save Product Image information into hidden file -> List image Name
    function saveImageInfo(fileOldName, fileNewName) {
        var productImageInfo = $('#txtProductImageInfo').val();
        var newInfo = "";
        if (productImageInfo == "" || productImageInfo == null) {
            newInfo = "[" + fileOldName + "/" + fileNewName + "]";
            $('#txtProductImageInfo').val(newInfo);
        }
        else {
            newInfo = ",[" + fileOldName + "/" + fileNewName + "]";
            productImageInfo = productImageInfo + newInfo;
            $('#txtProductImageInfo').val(productImageInfo);
        }
    }

    // Delete Product Image
    function removeImage(file) {
        var productCode = $('#txtProductCode').val();
        var productImageInfo = $('#txtProductImageInfo').val();
        var fd = new FormData();
        fd.append("fileImageName", file.name);
        fd.append("productCode", productCode);
        fd.append("productImageInfo", productImageInfo);
        var xhr = new XMLHttpRequest();
        xhr.open("POST", "@Url.Action("DeleteProductImage", "Product")", false);
        xhr.send(fd);
        if (xhr.readyState == 4 && xhr.status == 200) {
            showMessageDeleteImageSuccess();
            return true;
        }
        if (xhr.readyState == 4 && xhr.status != 200) {
            showMessageDeleteImageError();
            return false;
        }
    }

    function showMessageDeleteImageError() {
        jQuery.gritter.add({
            title: 'Thất bại!',
            text: 'Không thể xóa ảnh sản phẩm! Xin hãy thử lại!',
            class_name: 'growl-danger',
            sticky: false,
            time: '1000'
        });
        return false;
    }

    function showMessageDeleteImageSuccess() {
        jQuery.gritter.add({
            title: 'Thành công!',
            text: 'Xóa ảnh sản phẩm thành công!',
            class_name: 'growl-success',
            sticky: false,
            time: '1000'
        });
        return false;
    }

    // Save general product information
    function saveProductInfo() {
        if (jQuery("#frmProductDetail").valid()) {
            // Get selected BrandId
            var brandIdSelected = $("#cbbProductBrand option:selected").val();
            $("#txtBrandId").val(brandIdSelected);

            // Get selected Size
            var sizeId = $("#multiCbbProductSize").val();
            $("#txtListSizeId").val(sizeId);

            var genderId = $("#cbbGender option:selected").val();
            $("#txtGenderId").val(genderId);

            var productTypeId = $("#cbbProductType option:selected").val();
            $("#txtProductTypeId").val(productTypeId);

            // Get selected Size
            var locationId = $("#multiCbbProductLocation").val();
            $("#txtListLocationId").val(locationId);

            $.ajax({
                url: '@Url.Action("SaveProduct", "Product")',
                type: 'POST',
                dataType: 'json',
                data: $('#frmProductDetail').serialize(),
                success: function (data) {
                    if (data.Result == "@XukaShop.Common.CommonConst.SUCCESSFUL") {
                        showMessageSaveGeneralInfoSuccess();
                        // If success, fill the product code into ProductCode textbox
                        $('#txtProductCode').val(data.ProductCode);
                        $('#inputSizeQuantity').show();
                        $('#productImage').show();
                    } else {
                        showMessageSaveGeneralInfoError();
                        $('#txtProductCode').val("");
                    }
                },
                error: function () {
                    showMessageSaveGeneralInfoError();
                    $('#txtProductCode').val("");
                }
            });
            }
        }

        function showMessageSaveGeneralInfoError() {
            jQuery.gritter.add({
                title: 'Thất bại!',
                text: 'Không thể lưu thông tin sản phẩm! Xin hãy thử lại!',
                class_name: 'growl-danger',
                sticky: false,
                time: '1000'
            });
            return false;
        }

        function showMessageSaveGeneralInfoSuccess() {
            jQuery.gritter.add({
                title: 'Thành công!',
                text: 'Lưu thông tin sản phẩm thành công!',
                class_name: 'growl-success',
                sticky: false,
                time: '1000'
            });
            return false;
        }

        function loadProductSize() {
            var productCode = $('#txtProductCode').val();
            $.ajax({
                url: '@Url.Action("GetListProductSize", "Product")',
                type: 'POST',
                data: { productCode: productCode },
                success: function (data) {
                    $('#lstProductSize').html(data);
                },
                error: function () {
                    alert("Load Product Size Error");
                }
            });
        }

</script>
